//团购专场
const app = getApp();
var server = require('../../utils/server');
var common = require('../../utils/common');
var amapFile = require('../../libs/amap-wx');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollleft: '',
    curFirClassId: '',
    curFirName: '',
    totalCartNum: 0,
    lists: [],
    eventDetail: '',
    firClassList: [],
    isLogin: false,
    showLoginPop: false,
    isDisableLog: false,
    isLocate: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    this.data.eventid = options.eventid;
  },
  onPullDownRefresh() {
    this.getLocation();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getLocation();
  },
  getLocation() {
    wx.stopPullDownRefresh();
    if (app.globalData.longitude != null && app.globalData.latitude != null && app.globalData.city != "") {
      this.getUserInfo();
    } else {
      var gdMap = new amapFile.AMapWX({
        key: common.gdKey
      });
      gdMap.getRegeo({
        success: res => {
          app.globalData.location = res[0].regeocodeData.pois[0] == undefined ? res[0].name : res[0].regeocodeData.pois[0].name;
          app.globalData.longitude = res[0].longitude;
          app.globalData.latitude = res[0].latitude;
          app.globalData.city = res[0].regeocodeData.addressComponent.city;
          app.globalData.locateLongitude = res[0].longitude;
          app.globalData.locateLatitude = res[0].latitude;
          app.globalData.locateCity = res[0].regeocodeData.addressComponent.city;
          app.globalData.locateProvince = res[0].regeocodeData.addressComponent.province;
          this.getUserInfo();
          this.setData({
            isLocate: true
          })
          app.globalData.isLocate=true;
        },
        fail: info => {
          this.setData({
            isLocate: false
          })
          app.globalData.isLocate = false;
          wx.hideLoading();
        }
      })
    }

  },
  // 打开定位
  openLocation(e) {
    if (e.detail.errMsg == "openSetting:ok" && e.detail.authSetting['scope.userLocation']) {
      app.globalData.isLocate = true;
      this.setData({
        isLocate: true
      })
      this.getUserInfo();

    } else {
      common.showErrorToast('需要授权地理位置后使用！');
    }
  },
  getProducts(e) {
    var curtarget = e.currentTarget.dataset;
    this.setData({
      curFirClassId: curtarget.id,
      curFirName: curtarget.name,
      scrollleft: 'fir' + curtarget.id
    })
    this.getProductsList(curtarget.id);
  },
  // 商品数量增加
  addCount(e) {
    var curtarget = e.currentTarget.dataset;
    var goodsid = curtarget.id,
      goodsIndex = curtarget.index,
      quantity = curtarget.quantity;
    this.setData({
      ['lists[' + goodsIndex + '].isCanAdd']: false
    })
    server.postJSON(common.storePath + 'eventcart/add', {
      "event_id": this.data.eventid,
      "goods_id": goodsid,
      "quantity": 1
    }, res => {
      if (res.data.errno == "0") {
        this.setData({
          ['lists[' + goodsIndex + '].isCanAdd']: true,
          ['lists[' + goodsIndex + '].add_cart_num']: parseInt(quantity) + 1,
          totalCartNum:parseInt(this.data.totalCartNum)+1
        })
      } else {
        this.setData({
          ['lists[' + goodsIndex + '].isCanAdd']: true,
          ['lists[' + goodsIndex + '].add_cart_num']: parseInt(quantity)
        })
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  // 商品数量减少
  reduceCount(e) {
    var curtarget = e.currentTarget.dataset;
    var goodsid = curtarget.id,
      goodsIndex = curtarget.index,
      quantity = curtarget.quantity;
    this.setData({
      ['lists[' + goodsIndex + '].isCanReduce']: false,
    })
    if ((parseInt(quantity) - 1) > 0) {
      server.postJSON(common.storePath + 'eventcart/add', {
        "event_id": this.data.eventid,
        "goods_id": goodsid,
        "quantity": -1
      }, res => {
        if (res.data.errno == "0") {
          this.setData({
            ['lists[' + goodsIndex + '].isCanReduce']: true,
            ['lists[' + goodsIndex + '].add_cart_num']: parseInt(quantity) - 1,
            totalCartNum:parseInt(this.data.totalCartNum)-1
          })
        } else {
          this.setData({
            ['lists[' + goodsIndex + '].isCanReduce']: true
          })
          common.showErrorToast(res.data.errmsg);
        }
      })
    } else {
      var param = {
        "event_id": this.data.eventid,
        "goods_id": [goodsid]
      }
      server.postJSON(common.storePath + 'eventcart/delete', param, res => {
        if (res.data.errno == "0") {
          this.setData({
            ['lists[' + goodsIndex + '].isCanReduce']: true,
            ['lists[' + goodsIndex + '].add_cart_num']: 0,
            totalCartNum:parseInt(this.data.totalCartNum)-1
          })
        } else {
          this.setData({
            ['lists[' + goodsIndex + '].isCanReduce']: true
          })
          common.showErrorToast(res.data.errmsg);
        }
      })
    }

  },
  //修改商品数量
  updateGoodsNum(e) {
    var curtarget = e.currentTarget.dataset;
    var goodsid = curtarget.id,
      goodsIndex = curtarget.index,
      goodnum = e.detail.value,
      oldnum = curtarget.quantity;
    if (parseInt(goodnum) >= 1) {
      server.postJSON(common.storePath + 'eventcart/operate', {
        "event_id": this.data.eventid,
        "goods_id": goodsid,
        "quantity": goodnum
      }, res => {
        if (res.data.errno == "0") {
          this.setData({
            ['lists[' + goodsIndex + '].add_cart_num']: parseInt(goodnum)
          })
          this.getTotalCartNum();
        } else {
          this.setData({
            ['lists[' + goodsIndex + '].add_cart_num']: parseInt(oldnum)
          })
          common.showErrorToast(res.data.errmsg);
        }
      })
    } else if (parseInt(goodnum) == 0) {
      var param = {
        "event_id": this.data.eventid,
        "goods_id": [goodsid]
      }
      server.postJSON(common.storePath + 'eventcart/delete', param, res => {
        if (res.data.errno == "0") {
          this.setData({
            ['lists[' + goodsIndex + '].add_cart_num']: 0
          })
          this.getTotalCartNum();
        } else {
          common.showErrorToast(res.data.errmsg);
        }
      })
    }
  },
  //失去焦点获取商品数量
  getCurGoodsNum(e) {
    var curtarget = e.currentTarget.dataset;
    var eventId = curtarget.eventid,
      goodsid = curtarget.id,
      goodsIndex = curtarget.index,
      goodnum = e.detail.value,
      oldnum = curtarget.quantity;
    if (goodnum == '') {
      server.postJSON(common.storePath + 'eventcart/operate', {
        "event_id": this.data.eventid,
        "goods_id": goodsid,
        "quantity": 0
      }, res => {
        if (res.data.errno == "0") {
          console.log('修改成功');
          this.setData({
            ['lists[' + goodsIndex + '].add_cart_num']: 0
          })
          this.getTotalCartNum();
        } else {
          common.showErrorToast(res.data.errmsg);
        }
      })
    }
  },
  goToCart() {
    if (this.data.isLogin) {
      app.globalData.cartIndexType = 1;
      wx.navigateTo({
        url: '../../pages/cart/cartIndexSec',
      })
    } else {
      this.setData({
        showLoginPop: true
      })
    }
  },
  //获取用户信息
  getUserInfo() {
    var that = this;
    wx.login({
      success: resp => {
        wx.getUserInfo({
          success: res => {
            var code = resp.code;
            this.data.userParams = {
              "js_code": code,
              "encryptedData": res.encryptedData,
              "iv": res.iv,
              "userinfo": res.userInfo,
              "longitude": app.globalData.longitude,
              "latitude": app.globalData.latitude,
              "province": app.globalData.locateProvince,
              "city": app.globalData.locateCity
            }
            var that = this;
            server.login(common.basePath + 'miniprogram/login/', that.data.userParams, function (res) {
              if (res.data.errno == "0") {
                app.globalData.sso = res.data.data.sso;
                wx.setStorage({
                  key: "sso",
                  data: res.data.data.sso,
                  success: res => {
                    that.getCategoryList();
                    that.getTotalCartNum();
                    that.setData({
                      isLogin: true
                    })
                    app.globalData.isGetWxUserinfo = true;
                  }
                })
              } else {
                that.setData({
                  isLogin: false
                })
                common.showErrorToast(res.data.errmsg);
              }
            })
          },
          fail: res => {
            this.getCategoryList();
            this.setData({
              isLogin: false
            })

          }
        })
      },
      fail: res => {
        this.getCategoryList();
        this.setData({
          isLogin: false
        })
      }
    })
  },
  getCategoryList() {
    server.postJSON(common.storePath + 'event/category/', {
      "event_id": this.data.eventid
    }, res => {
      if (res.data.errno == '0') {
        var category_list = res.data.data.category_list;
        this.setData({
          firClassList: category_list,
          curFirClassId: category_list[0].category_id,
          curFirName: category_list[0].name
        })
        this.getProductsList(category_list[0].category_id);
      } else {
        common.showErrorToast(res.data.errmsg)
      }
    })
  },
  getProductsList(classid) {
    server.postJSON(common.storePath + 'event/detail/', {
      "event_id": this.data.eventid,
      "category_id": classid
    }, res => {
      if (res.data.errno == '0') {
        var lists = res.data.data.goods,
          eventDetail = res.data.data.event;
        lists.forEach((list, idx) => {
          list.isCanAdd = true;
          list.isCanReduce = true;
        })
        this.setData({
          lists: lists,
          eventDetail: eventDetail
        })
      } else {
        common.showErrorToast(res.data.errmsg)
      }
    })
  },
  hideLoginPop() {
    this.setData({
      showLoginPop: false
    })
  },
  showAgreement() {
    wx.navigateTo({
      url: '../../pages/common/agreement',
    })
  },
  login(e) {
    this.setData({
      isDisableLog: true
    })
    if (e.detail.errMsg == "getUserInfo:ok") {
      this.setData({
        showLoginPop: false
      })
      var that = this
      wx.login({
        success: resp => {
          wx.getUserInfo({
            success: res => {
              var code = resp.code;
              this.data.userParams = {
                "js_code": code,
                "encryptedData": res.encryptedData,
                "iv": res.iv,
                "userinfo": res.userInfo,
                "longitude": app.globalData.longitude,
                "latitude": app.globalData.latitude,
                "province": app.globalData.locateProvince,
                "city": app.globalData.city
              }
              var that = this;
              server.login(common.basePath + 'miniprogram/login/', this.data.userParams, function (res) {
                if (res.data.errno == "0") {
                  wx.setStorage({
                    key: "sso",
                    data: res.data.data.sso,
                    success: res => {
                      that.getProductsList(that.data.curFirClassId);
                      that.getTotalCartNum();
                      that.setData({
                        isLogin: true
                      })
                      app.globalData.isGetWxUserinfo = true;
                      common.showErrorToast('登录成功')
                      that.setData({
                        isDisableLog: false
                      })
                    }
                  })
                } else {
                  that.setData({
                    isDisableLog: false
                  })
                  common.showErrorToast(res.data.errmsg)
                }
              })
            }
          })
        }
      })
    } else {
      this.setData({
        isDisableLog: false
      })
      wx.showToast({
        icon: 'none',
        title: '需要授权用户信息使用元初到家！'
      })
    }
  },
  //本地存储用户信息
  storageUserinfo(data) {
    wx.setStorage({
      key: "userInfo",
      data: data
    })
  },
  getTotalCartNum() {
    server.postJSON(common.storePath + 'eventcart/num', '', res => {
      var res = res.data;
      if (res.errno == "0") {
        this.setData({
          totalCartNum: res.data
        })
      } else {
        if (res.errno == '100012' || res.errno == '100013') {
          this.setData({
            isLogin: false
          })
        } else {
          this.setData({
            isLogin: true
          })
          common.showErrorToast(res.errmsg);
        }
      }
    })
  },
  goToLogin() {
    this.setData({
      showLoginPop: true
    })
  }, 
   //分享事件
  onShareAppMessage(option) {
  }
})